package com.renwei.yunlong.activity.news;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.fingdo.statelayout.StateLayout;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.me.KnowInformationActivity;
import com.renwei.yunlong.activity.me.ObjectInformationtActivity;
import com.renwei.yunlong.activity.work.ComplaintsInformationActivity;
import com.renwei.yunlong.activity.work.SpareInformationActivity;
import com.renwei.yunlong.activity.work.WorkInformationActivity;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.MsgDealBean;
import com.renwei.yunlong.event.MessageRefreshEvent;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DateTimeUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.RoundView;
import com.renwei.yunlong.view.SimpleOptionView;
import com.renwei.yunlong.view.SwipeMenuLayout;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;
import com.zyf.fwms.commonlibrary.utils.GlideCircleTransform;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

public class MessageDealActivity extends BaseActivity implements BaseRecyclerViewAdapter.OnItemClickLitener,
        XRecyclerView.LoadingListener, HttpTaskListener {

    private static final String TYPE = "type";
    private static final String CONTENT = "content";
    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.recyview)
    XRecyclerView recyclerView;
    @Bind(R.id.state_layout)
    StateLayout stateLayout;
    private String content;
    private String type;
    private int page = 1;
    private DealAdapter adapter;
    private int mPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_deal);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        type = getIntent().getStringExtra(TYPE);
        content = getIntent().getStringExtra(CONTENT);

        initView();
        initData();
    }

    private void initView() {
        String name = "";
        switch (type.substring(0, 1)) {
            //0工单1问题 2投诉 3对象 4备件 5项目 6企业
            case "0":
                name = "工单";
                break;
            case "1":
                if ("16".equals(type)){
                    name = "知识";
                }else{
                    name = "问题";
                }
                break;
            case "2":
                name = "投诉";
                break;
            case "3":
                name = "对象";
                break;
            case "4":
                name = "备件";
                break;
            case "5":
                name = "项目";
                break;
            case "6":
                name = "系统";
                break;
            default:
                break;
        }
        simpleTileView.setTitle(name + "提醒");

        adapter = new DealAdapter(this);
        adapter.setOnItemClickLitener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setLoadingListener(this);
        recyclerView.setAdapter(adapter);
    }

    private void initData() {

        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("receiverCompanyCode", ownerBean.getRows().getOwnerCode());
            map.put("receiverId", ownerBean.getRows().getEmployeeId());
        } else {
            map.put("receiverCompanyCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("receiverId", serviceLoginBean.getRows().getEmployeeId());
        }
        map.put("type", type);
        map.put("page", page + "");
        map.put("rows", "20");
        map.put("content", content);
        ServiceRequestManager.getManager().getMsgList(this, JsonMapUtil.mapToJson(map), this);
    }


    @Override
    public void onItemClick(View view, int position) {
        mPosition = position;
        MsgDealBean.RowsBean item = adapter.getItem(position);
        switch (view.getId()) {
            case R.id.rl_root:
                // 点击跳转
                itemClickByType(item);
                break;
            case R.id.btn_read:
                if ("0".equals(item.getStatus())) {
                    item.setStatus("1");
                    messageState(item.getMessageId(), 1);
                } else {
                    item.setStatus("0");
                    messageState(item.getMessageId(), 2);
                }
                adapter.notifyItemChanged(position + 1);
                break;
            case R.id.btn_delete:
                messageState(item.getMessageId(), 0);
                break;
        }

    }

    private void itemClickByType(MsgDealBean.RowsBean bean) {
        switch (type.substring(0, 1)) {
            //0工单1问题 2投诉 3对象 4备件 5项目 6企业
            case "0": // 工单OK
                WorkInformationActivity.OpenActivity(this, bean.getRelationId(), bean.getServerId() + "", bean.getOutsourceFlag());
                break;
            case "1": // 问题 OK
                if ("16".equals(bean.getType())){
                    KnowInformationActivity.OpenActivity(this,bean.getRelationId());
                }else{
                    ProblemInformationActivity.OpenActivity(this, bean.getRequestId() + "", bean.getRelationId(), bean.getOutsourceFlag());
                }
                break;
            case "2": // 投诉
                ComplaintsInformationActivity.OpenActivity(this, bean.getRequestId() + "", bean.getNewRequestId() + "",
                        bean.getServerRequestId() + "", bean.getServerId() + "", bean.getOutsourceFlag(), bean.getRelationId(), bean.getRequestUserName());
                break;
            case "3": //对象 OK
                ObjectInformationtActivity.OpenAcitivity(this, "对象详情", bean.getOutsourceFlag(), bean.getRelationId(),bean.getAssetName());
                break;
            case "4": // 备件 OK
                if ("4".equals(bean.getType())){
                    ObjectInformationtActivity.OpenAcitivity(this, "备件详情", bean.getOutsourceFlag(), bean.getRelationId(),bean.getAssetName());
                }else{
                    SpareInformationActivity.OpenActivity(this, bean.getRequestId() + "", bean.getOutsourceFlag(), bean.getRelationId());
                }
                break;
            default:
                MessageDetailActivity.OpenActivity(mContext, bean.getMessageId());
                break;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("messageId", bean.getMessageId() + "");
        ServiceRequestManager.getManager().getMessageDetail(this, JsonMapUtil.mapToJson(map), this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new MessageRefreshEvent(true));
    }

    /**
     * @param messageId
     * @param flag      0删除 1已读 2未读
     */
    private void messageState(int messageId, int flag) {
        HashMap<String, String> map = new HashMap<>();
        map.put("messageId", messageId + "");
        map.put("deleteFlag", flag + "");
        ServiceRequestManager.getManager().setMessageState(this, JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        recyclerView.setLoadingMoreEnabled(false);
        adapter.clean();
        initData();
    }

    @Override
    public void onLoadMore() {
        page++;
        initData();
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                recyclerView.loadMoreComplete();
                recyclerView.refreshComplete();
                MsgDealBean bean = new Gson().fromJson(result, MsgDealBean.class);
                if (bean.getMessage().getCode() == 200) {
                    if (bean.getRows().size() < 20) {
                        recyclerView.setLoadingMoreEnabled(false);
                    }
                    adapter.addAll(bean.getRows());
                    if (adapter.getData().size() == 0) {
                        stateLayout.showEmptyView();
                    } else {
                        stateLayout.showContentView();
                    }
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        switch (requestId) {
            case 1:
                page--;
                recyclerView.loadMoreComplete();
                recyclerView.refreshComplete();
                stateLayout.showErrorView();
                break;
            default:
                break;
        }
    }

    class DealAdapter extends BaseRecyclerViewAdapter<MsgDealBean.RowsBean> {

        public DealAdapter(Context context) {
            super(context);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(inflater.inflate(R.layout.item_message_deal, parent,false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final MsgDealBean.RowsBean item = getItem(position);
            final ViewHolder viewHolder = (ViewHolder) holder;
            if (item != null) {
                if ("0".equals(item.getStatus())) {
                    viewHolder.ivBot.setVisibility(View.VISIBLE);
                    viewHolder.tvRead.setText("已读");
                } else {
                    viewHolder.ivBot.setVisibility(View.GONE);
                    viewHolder.tvRead.setText("未读");
                }
                viewHolder.tvContent.setText(item.getContent());
                String name = "";
                if (!TextUtils.isEmpty(item.getSendCompanyName())) {
                    if ("系统".equals(item.getSenUserName())) {
                        name = item.getSenUserName();
                        Glide.with(mContext).load(R.mipmap.icon_xitong).transform(new GlideCircleTransform(mContext)).into(viewHolder.ivHead);
                    } else {
                        name = name + item.getSendCompanyName();
                        if (!TextUtils.isEmpty(item.getSenUserName())) {
                            name = name + "/" + item.getSenUserName();
                        }
                        if (!TextUtils.isEmpty(item.getMobilePhone())) {
                            name = name + "/" + item.getMobilePhone();
                        }
                        try {
                            if ("1".equals(type.substring(0, 1))) {
                                name = name.substring(item.getSendCompanyName().length() + 1, name.length());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if ("1".equals(companyType)) {
                            Glide.with(mContext).load(Api.$().OWNER_FILE_URL + item.getAvatar()).placeholder(R.mipmap.icon_header_default)
                                    .error(R.mipmap.icon_header_default).transform(new GlideCircleTransform(mContext)).into(viewHolder.ivHead);
                        } else if ("2".equals(companyType)) {
                            Glide.with(mContext).load(Api.$().SERVICE_FILE_URL + item.getAvatar()).placeholder(R.mipmap.icon_header_default)
                                    .error(R.mipmap.icon_header_default).transform(new GlideCircleTransform(mContext)).into(viewHolder.ivHead);
                        }
                    }
                } else {
                    Glide.with(mContext).load(R.mipmap.icon_xitong).transform(new GlideCircleTransform(mContext)).into(viewHolder.ivHead);
                    name = "系统";
                }

                viewHolder.tvName.setText(name);
                if (!TextUtils.isEmpty(item.getCreateDate())) {
                    viewHolder.tvTime.setText(DateTimeUtils.stampToDateNow(DateTimeUtils.string2Long
                            (item.getCreateDate().replace("T", " "), "yyyy-MM-dd HH:mm:ss")));
                }
                viewHolder.rlRoot.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        item.setStatus("1");
                        viewHolder.ivBot.setVisibility(View.GONE);
                        mOnItemClickLitener.onItemClick(v, position);
                    }
                });
                viewHolder.tvRead.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mOnItemClickLitener.onItemClick(view, position);
                        viewHolder.smlayout.smoothClose();
                    }
                });
                viewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mOnItemClickLitener.onItemClick(view, position);
                        viewHolder.smlayout.smoothClose();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                removeData(position);
                            }
                        }, 100);
                    }
                });
            }
        }
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.iv_head)
        ImageView ivHead;
        @Bind(R.id.iv_bot)
        RoundView ivBot;
        @Bind(R.id.rl_iv)
        RelativeLayout rlIv;
        @Bind(R.id.tv_time)
        TextView tvTime;
        @Bind(R.id.tv_name)
        TextView tvName;
        @Bind(R.id.tv_content)
        TextView tvContent;
        @Bind(R.id.rl_root)
        RelativeLayout rlRoot;
        @Bind(R.id.btn_read)
        TextView tvRead;
        @Bind(R.id.btn_delete)
        TextView tvDelete;
        @Bind(R.id.smlayout)
        SwipeMenuLayout smlayout;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    /**
     * @param context
     * @param type    消息类型
     * @param content 搜索关键词  没有就传""
     */
    public static void OpenActivity(Context context, String type, String content) {
        Intent intent = new Intent(context, MessageDealActivity.class);
        intent.putExtra(TYPE, type);
        intent.putExtra(CONTENT, content);
        context.startActivity(intent);
    }
}
